package screenpac.controllers;

import java.awt.Color;
import java.util.LinkedList;

import screenpac.extract.Constants;
import screenpac.features.GaiAStarSearch;
import screenpac.features.GaiNearFarPillDistance;
import screenpac.features.GaiRandomPill;
import screenpac.features.NearestPillDistance;
import screenpac.features.Utilities;
import screenpac.model.GameStateInterface;
import screenpac.model.GhostState;
import screenpac.model.Node;

public class GaiAstarSimplePillEater implements AgentInterface, Constants {
    /*
    This simple pill eater just heads for the nearest pill each time
     */
    GaiNearFarPillDistance npd;
    GaiRandomPill randPill;
    GaiAStarSearch aSearch;
    int ghostPathScore[];
    boolean needTarget = true;
    Node next = null;
    Node target;
   
    public GaiAstarSimplePillEater() {
        npd = new GaiNearFarPillDistance();
        randPill = new GaiRandomPill();
        aSearch = new GaiAStarSearch();
    }

    public int action(GameStateInterface gs) {
        // choose the adjacent current with the
        // nearest pill
        // check that copying works!
        gs = gs.copy();
        Node current = gs.getPacman().current;

        //npd.score(gs, current);
        //Node target = npd.closest;
        if(needTarget){
        	randPill.score(gs, current);
        	target = randPill.randNode;
        	needTarget = false;
        }
       
        //Find best path to get the closest pill
        LinkedList<Node>  path = aSearch.findPath(current, target, gs);

        Node next = null;
        
        //Coloring the A* path
        if(path != null) {
        	for(Node n: path) {
        		if(n != target) {
        			n.col = Color.BLUE;
        		}	
        	}  	
        } else {
        	System.out.println("PATH IS NULL!!!");
        }
        
        //next = path.getFirst();
    	if(path.size() > 0) {
    		//System.out.println("path size: " + path.size());
    		next = path.getFirst();
    		
    		if(path.size() == 1) {
    			needTarget = true;
    		} 		
    	} else {
    		//Arrived at target!
    		needTarget = true;
    	}
        
        
        //Find Ghost distances
        /*for(GhostState ghost: gs.getGhosts()) {
        	int distance = gs.getMaze().dist(gs.getPacman().current, ghost.current);
        	System.out.println("Dist: " + distance);
        }*/
        
        //Node next = Utilities.getClosest(current.adj, npd.closest, gs.getMaze());
      //debug
        if(target == null) {
        	System.out.println("TARGET IS NULL");
        }
        if(next == null) {
        	System.out.println("NEXT IS NULL");
        }
        int dir = Utilities.getWrappedDirection(current, next, gs.getMaze());
        return dir;
    }
}
